package com.miniapp.controller;

import com.alibaba.fastjson.JSONObject;
import com.miniapp.entity.MiniAttachmentEntity;
import com.miniapp.service.MiniAttachmentService;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.FtpUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UploadController  extends AbstractController {
	private static Logger logger = LoggerFactory.getLogger(UploadController.class);
	@Autowired
	MiniAttachmentService miniAttachmentService;
	@Value("${venice.local_path}")
	private String LOCAL_PATH;
	//通用型上传,续传类型,会作为文件的路径目录.如upload/{type}/{filename}
	//type=类型，目的性的，不要用前面人取得，这个会作为目录区分
	@RequestMapping(value = "/upload",produces = "text/html; charset=utf-8")
	@ResponseBody
	public String upload(@RequestParam("file") MultipartFile file, HttpServletResponse response, @RequestParam String type,@RequestParam String media){
		JSONObject result = new JSONObject();
		try {
			Long userId = this.getUserId();
			//文件名:时间戳+_+随机数+原后缀
			String saveFileName = System.currentTimeMillis()+"_"+ RandomStringUtils.randomNumeric(4)
					+ "." + FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
			//支持IE8增加报文头
			response.setHeader("X-Frame-Options","SAMEORIGIN");
			//路径 upload+type+filename
			String saveFilePath = "upload/" + type + "/"+ BaseUtils.getDateString(new Date(),new SimpleDateFormat("yyyyMMdd")) + saveFileName;
			MiniAttachmentEntity miniAttachment = miniAttachmentService.createAttachment(file.getOriginalFilename(),
					saveFilePath, file.getInputStream(),media,userId);
			result.put("result","success");
			result.put("id", miniAttachment.getId());
			result.put("file_url", miniAttachmentService.getFullRequestUrl(miniAttachment));
		}catch (Exception e){
			logger.error("上传出错",e);
			result.put("result","error");
			result.put("msg",e.getMessage());
		}
		return result.toJSONString();
	}
	@RequestMapping(value = "/upload_url",produces = "text/html; charset=utf-8")
	@ResponseBody
	public String uploadUrl(@RequestParam("file") MultipartFile file, HttpServletResponse response, @RequestParam String type){
		JSONObject result = new JSONObject();
		try {
			//文件名:时间戳+_+随机数+原后缀
			String saveFileName = System.currentTimeMillis()+"_"+ RandomStringUtils.randomNumeric(4)
					+ "." + FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
			//支持IE8增加报文头
			response.setHeader("X-Frame-Options","SAMEORIGIN");
			//路径 upload+type+filename
			String saveFilePath = "upload/" + type + "/"+ BaseUtils.getDateString(new Date(),new SimpleDateFormat("yyyyMMdd")) + saveFileName;
			String url = miniAttachmentService.upload(file.getOriginalFilename(),
					saveFilePath, file.getInputStream());
			result.put("result","success");
			result.put("file_url", url);
			result.put("path",saveFilePath);
		}catch (Exception e){
			logger.error("上传出错",e);
			result.put("result","error");
			result.put("msg",e.getMessage());
		}
		return result.toJSONString();
	}
	@RequestMapping(value = "/upload_ftp",produces = "text/html; charset=utf-8")
	@ResponseBody
	public String uploadFtp(@RequestParam("file") MultipartFile file, HttpServletResponse response, @RequestParam String type){
		JSONObject result = new JSONObject();
		try {
			//文件名:时间戳+_+随机数+原后缀
			String saveFileName = System.currentTimeMillis()+"_"+ RandomStringUtils.randomNumeric(4)
					+ "." + FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
			//支持IE8增加报文头
			response.setHeader("X-Frame-Options","SAMEORIGIN");
			//路径 upload+type+filename
			String saveFilePath = this.getAppid() +"_"+ saveFileName;
			boolean flag = FtpUtil.uploadFile(saveFilePath, file.getInputStream());
			if (!flag){
				result.put("result","error");
			}else {
				result.put("result","success");
				result.put("file_url",saveFilePath);
			}
		}catch (Exception e){
			logger.error("上传出错",e);
			result.put("result","error");
			result.put("msg",e.getMessage());
		}
		return result.toJSONString();
	}
	@RequestMapping(value = "/upload_local",produces = "text/html; charset=utf-8")
	@ResponseBody
	public String uploadLocal(@RequestParam("file") MultipartFile file, HttpServletResponse response, @RequestParam String type){
		JSONObject result = new JSONObject();
		try {
			//文件名:时间戳+_+随机数+原后缀
			String saveFileName = System.currentTimeMillis()+"_"+ RandomStringUtils.randomNumeric(4)
					+ "." + FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
			//支持IE8增加报文头
			response.setHeader("X-Frame-Options","SAMEORIGIN");
			//路径 upload+type+filename
			String saveFilePath = this.getAppid() +"_"+ saveFileName;
			File uploadFile = new File(LOCAL_PATH, saveFilePath);
			OutputStream out = new FileOutputStream(uploadFile);
			InputStream in = file.getInputStream();
			byte[] buffer = new byte[1024 * 1024];
			int length;
			while ((length = in.read(buffer)) > 0) {
				out.write(buffer, 0, length);
			}
			in.close();
			out.close();
			result.put("result","success");
			result.put("file_url",saveFilePath);
		}catch (Exception e){
			logger.error("上传出错",e);
			result.put("result","error");
			result.put("msg",e.getMessage());
		}
		return result.toJSONString();
	}
}
